<template>
  <!-------- 植物列表 -------->
  <div class="plant-list">
    <!-- 顶部部分 -->
    <div class="plant_head">
      <!-- 左侧筛选 -->
      <div class="filter_box">
        <el-button
          @click="handleEditModuleBtn"
          :class="{ active_repeat: queryParams.repeat == 1 }"
        >
          {{ "植物查重" }}
        </el-button>

        <div class="search_box">
          <el-input v-model="queryParams.message" placeholder="请输入" />
          <el-icon><Search /></el-icon>
        </div>
      </div>

      <!-- 右侧新增下载 -->
      <div class="labor">
        <!-- <span @click="handleClickDownloadTemplate">模板下载</span> -->

        <!-- 下拉菜单 -->
        <el-dropdown trigger="click" @command="handleCommand">
          <el-button icon="Plus">
            {{ "新增植物" }}
          </el-button>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="add">新增植物</el-dropdown-item>
              <el-dropdown-item command="all">批量新增</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 内容部分 -->
    <div class="plant_content">
      <div class="item_box">
        <!-- 每一个植物 -->
        <div
          class="plant_item"
          @contextmenu.prevent="setSelectTag(item, index)"
          v-for="(item, index) in plansListData"
          :key="index"
          :class="{ active_item: index == activeIndex }"
          @click.stop="handlePlanDetails(item, index)"
        >
          <img :src="item.plantUrl" alt="" />
          <p>{{ item.plantName }}</p>
        </div>
      </div>

      <!-- 分页 -->
      <pagination
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.size"
        @pagination="hanleGetPlanList"
      />
    </div>

    <!-- 批量操作弹窗 -->
    <BatchUploadDialog
      v-model="isUploadDialog"
      @download="handleClickDownloadTemplate"
      @batchUpload="handleFileChange"
    ></BatchUploadDialog>

    <!-- 抽屉 -->
    <DrawerPlan v-model="isShowDrawer" :itemData="itemData"></DrawerPlan>

    <!-- 右键菜单 -->
    <ul
      v-show="contextmenu.visible"
      :style="{ left: contextmenu.left + 'px', top: contextmenu.top + 'px' }"
      class="contextmenu"
      @click.passive.stop
    >
      <li @click="handleOpenEdit()">编辑</li>
      <li @click="handleDeletePlant(showInp)">删除</li>
    </ul>
  </div>
</template>

<script setup>
import { inject, onMounted, onUnmounted, ref, watch } from "vue";
import DrawerPlan from "./DrawerPlan.vue";
// 批量上传下载
import { importExcel, exportExcel } from "@/utils/peak-tools";
// 批量上传弹窗
import BatchUploadDialog from "@/components/BatchUploadDialog";

// 后端接口
import { GetPlansList, DeletePlans, addPlans } from "@/api/plans";
// EelementUI
import { ElMessage, ElMessageBox } from "element-plus";

const editPlanItem = inject("editPlanItem");
const emits = defineEmits(["editPlan", "ShowHidePlant"]);

const props = defineProps({
  // 分类数据
  categoryList: {
    type: Array,
    default: () => [],
  },

  activeCategory: {
    type: Object,
    default: () => {},
  },

  plantTypeId: {
    type: Number,
    default: 0,
  },
});

const plansListData = ref([]); // 植物数据
const isShowDrawer = ref(false); // 抽屉状态
const isUploadDialog = ref(false); // 批量操作弹窗
const uploadRef = ref(null); // 上传

// 右键菜单属性
const contextmenu = ref({
  left: 0,
  top: 0,
  visible: false,
});

const activeIndex = ref(-1); // 高亮选中
const total = ref(0); // 总条数
const data = reactive({
  itemData: {},

  queryParams: {
    page: 1,
    size: 10,
    repeat: "", // 1 -- 植物查重
    plantTypeId: 0, // 分类id
    message: null, // 搜索的值
  },
});

const { queryParams, itemData } = toRefs(data);

const queryParamsComputed = computed(() => {
  queryParams.value.plantTypeId = props.plantTypeId;
  return { ...queryParams.value };
});

watch(
  () => queryParamsComputed.value,
  (value) => hanleGetPlanList(),
  { deep: true }
);

onMounted(() => {
  document.body.addEventListener("click", closeContextmenu); // 组件加载完毕后 给Body添加事件
  hanleGetPlanList(); // 查询植物列表
});

/** 组件销毁生命周期 */
onUnmounted(() => {
  document.body.removeEventListener("click", closeContextmenu);
});

/*** 植物查重 ***/
const handleEditModuleBtn = () => {
  queryParams.value.repeat = queryParams.value.repeat == 1 ? "" : 1;
};

/*** 普通新增/批量新增 ***/
const handleCommand = (val) => {
  if (val === "add") return emits("ShowHidePlant", true); // 显示普通新增
  isUploadDialog.value = true; // 显示批量操作 模态框
};

/*** 查询植物列表 ***/
const hanleGetPlanList = async () => {
  const { data } = await GetPlansList(queryParams.value);
  total.value = data.total;

  plansListData.value = data.records;
};

/** 点击植物 出现模态框 **/
const handlePlanDetails = (item, index) => {
  activeIndex.value = index;
  isShowDrawer.value = true; // 显示抽屉
  contextmenu.value.visible = false; // 隐藏右键菜单

  itemData.value = { ...item };
};

// 模板头部
const tableTemplateHead = ref({
  植物名称: "plantName",
  "植物分类(请设置已经有的分类)": "plantClassName",
  科: "plantFamilies",
  属: "plantProperty",
  基本特征: "plantCharacteristics",
  生长习性: "palntHabitGrowth",
  生态角色: "plantRoleEcology",
  养护需求: "palntMaintenanceNeeds",
  文化寓意: "palntCulturalImplication",
  繁殖方法: "palntMethodsReproduction",
  病虫害防治: "plantPestDiseaseControl",
});

// 模板数据
const tableTemplateData = ref([
  {
    plantName: "芭蕉树",
    plantClassName: "草木",
    plantFamilies: "芭蕉科",
    plantProperty: "芭蕉属",
    plantCharacteristics: "多年生草本植物。高2.5~4m，根茎较长",
    palntHabitGrowth: "芭蕉最适宜植于小型庭院的一角或窗前墙边",
    plantRoleEcology: "不宜成行栽植，宜散点或几株丛植",
    palntMaintenanceNeeds: "芭蕉的繁殖主要采用吸芽分株繁殖。吸芽宜选茎粗壮....",
    palntCulturalImplication: "茎可入药，利..",
    palntMethodsReproduction: "播前要精细整地，除净杂草。在..",
    plantPestDiseaseControl: "与杂草竞争力弱..",
  },
]);

/** 下载模板 **/
const handleClickDownloadTemplate = () => {
  exportExcel(
    "植物库模板数据.xlsx",
    tableTemplateHead.value,
    tableTemplateData.value
  );
};

/** 批量上传 **/
const handleFileChange = async (file) => {
  const result = await importExcel(file.raw, tableTemplateHead.value); // 导入Excel格式化数据

  // 没有返回数据 直接 return 并提示
  if (!result.data) return ElMessage.error(result.msg);

  const msg = validateData(result.data) // 数据验证

  // 校验未通过就拦截
  if (msg) {
    ElMessage.error(msg);
    return;
  }

  // 添加接口
  await addPlans(result.data);
  ElMessage.success("上传成功");
  isUploadDialog.value = false // 隐藏批量操作
  hanleGetPlanList(); // 查询植物列表
};

/** 数据验证函数 **/
const validateData = (data) => { 
  for (const [index, item] of data.entries()) {
    const category = props.categoryList.find(
      (cat) => cat.plantTypeName == item.plantClassName
    );

    item.plantTypeId = category?.id; // 赋值分类id
    item.plantUrl = "http://119.91.22.164:8085/images/defaultImg.png"; // 赋值默认植物图片

    if (!category) {
      return `第${index + 1}条植物分类不存在`;
    }

    if (!item?.plantName?.trim()) {
      return `第${index + 1}条植物名称不能为空`;
    }

    if (!item?.plantFamilies?.trim()) {
      return `第${index + 1}条科不能为空`;
    }

    if (!item?.plantProperty?.trim()) {
      return `第${index + 1}条属不能为空`;
    }

    if (item?.plantName?.length > 10) {
      return `第${index + 1}条植物名称超过10个字符`;
    }

    if (item?.plantFamilies?.length > 10) {
      return `第${index + 1}条科超过10个字符`;
    }

    if (item?.plantProperty?.length > 10) {
      return `第${index + 1}条属超过10个字符`;
    }
  }
  return null; // 数据验证通过
};

/** 右键事件 */
const setSelectTag = (item, index) => {
  contextmenu.value.left = event.x;
  contextmenu.value.top = event.y;
  contextmenu.value.visible = true;
  activeIndex.value = index; // 高亮
  itemData.value = { ...item }; // 赋值当前数据
};

/** 右键删除 **/
const handleDeletePlant = () => {
  contextmenu.value.visible = false;

  ElMessageBox.confirm("提示", "确定要删除该植物吗？", {
    type: "warning",
  }).then(() => {
    // 删除接口
    DeletePlans([itemData.value.id]).then((res) => {
      hanleGetPlanList(); //查询植物列表
      ElMessage({ type: "success", message: "删除成功" });
    });
  });
};

/** 右键编辑 **/
const handleOpenEdit = () => {
  editPlanItem(true, itemData.value); // 显示编辑模块传递数据
  contextmenu.value.visible = false;
};

/** 隐藏右键菜单 */
const closeContextmenu = () => {
  // 点击模态框的时候
  if (event.target.classList.contains("el-overlay-dialog")) return;

  activeIndex.value = -1; // 取消高亮
  contextmenu.value.visible = false; // 隐藏菜单
  isShowDrawer.value = false;
};

defineExpose({
  hanleGetPlanList,
});
</script>

<style lang="scss" scoped>
.plant-list {
  width: 100%;
  min-width: 300px;
  background-color: #fff;
  border-radius: 10px 10px 10px 10px;
  padding-bottom: 20px;
  min-height: 780px;

  .plant_head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 78px;
    padding: 0 32px;
    color: #696969;
    font-size: 18px;
    border-bottom: 1px solid #ccc;

    /** 左侧筛选 */
    .filter_box {
      display: flex;

      button {
        padding: 0;
        width: 112px;
        height: 40px;
        text-align: center;
        font-size: 14px;
        color: #5974ff;
        border-radius: 6px;
        background: transparent;
        border: 1px solid #5974ff;

        &:hover {
          opacity: 0.8;
        }

        &.active_repeat {
          background: #5974ff;
          color: #fff;
        }
      }

      .search_box {
        display: flex;
        margin-left: 24px;
        align-items: center;

        ::v-deep(.el-input) {
          width: 230px;
          .el-input__wrapper {
            height: 40px;
            border-radius: 2px !important;
            background-color: #f5f5f5;
            box-shadow: none;
          }
        }

        i {
          display: inline-block;
          width: 40px;
          height: 40px;
          text-align: center;
          line-height: 44px;
          color: #fff;
          background: #5974ff;
          border-radius: 0px 6px 6px 0px;
          cursor: pointer;
          flex-shrink: 0;
        }
      }
    }

    /**右侧新增下载  */
    .labor {
      display: flex;
      align-items: center;

      span {
        font-size: 16px;
        color: #44bd60;
        cursor: pointer;

        &:hover {
          opacity: 0.8;
        }
      }

      button {
        width: 144px;
        height: 40px;
        font-size: 16px;
        background: #5974ff;
        color: #fff;
        padding: 0;
        border: 0;
        border-radius: 6px 6px 6px 6px;
        margin-left: 40px;

        &:hover {
          opacity: 0.9;
        }
      }
    }
  }

  /** 内容部分 */
  .plant_content {
    padding: 32px;

    .item_box {
      display: flex;
      flex-wrap: wrap;

      column-gap: 18px;

      .plant_item {
        text-align: center;
        cursor: pointer;

        &.active_item {
          img {
            border: 1px solid #f99d38;
          }
          p {
            color: #f99d38;
          }
        }

        img {
          width: 230px;
          height: 160px;
          object-fit: cover;
          border: 1px solid transparent;
          border-radius: 10px 10px 10px 10px;
        }

        p {
          margin: 14px 0 28px;
          font-size: 18px;
          color: #363636;
        }
      }
    }
  }

  /** 右键菜单 */
  .contextmenu {
    margin: 0;
    width: 140px;
    background: #fff;
    z-index: 3000;
    list-style-type: none;
    padding: 16px 0 20px;
    font-size: 14px;
    font-weight: 400;
    color: #696969;
    text-align: center;
    position: fixed;
    backdrop-filter: blur(10px);
    letter-spacing: 2px;
    border-radius: 6px 6px 6px 6px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.2);
  }

  .contextmenu li {
    margin: 0;
    height: 40px;
    line-height: 40px;
    cursor: pointer;
    color: #696969;
  }

  .contextmenu li:hover {
    color: #363636;
    background: #eeeeee;
  }
}

// 批量上传
.upload-plant {
  width: 100%;
  text-align: center;

  ::v-deep(.el-upload) {
    width: 100%;

    .el-upload-list {
      display: none;
    }
  }
}
</style>
